package com.atguigu.springboot.springbootdemo.config;

import com.atguigu.springboot.springbootdemo.EsUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EsConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        HttpHost[] httpHosts = EsUtils.getElasticSearchHttpHosts("127.0.0.1:9200");
        RestClientBuilder restClientBuilder = RestClient.builder(httpHosts).setRequestConfigCallback(requestConfigBuilder-> {
            //设置连接超时时间
            requestConfigBuilder.setConnectTimeout(1000);
            requestConfigBuilder.setSocketTimeout(30000);
            //连接的超时时间
            requestConfigBuilder.setConnectionRequestTimeout(500);
            return requestConfigBuilder;
        }).setHttpClientConfigCallback(httpClientBuilder -> {
            httpClientBuilder.disableAuthCaching();
            httpClientBuilder.setKeepAliveStrategy((response, context) -> 60 * 1000);
            //设置账密
            return EsUtils.getHttpAsyncClientBuilder(httpClientBuilder, "username", "password");
        });
        return new RestHighLevelClient(restClientBuilder);
    }
}
